package com.athbsd.TreeSet;

import com.athbsd.exer4.Student;
import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * Date:2025/2/24
 * Author：zhouzhou
 * Description:对象排序的两种方式,自然排序,定制排序
 */
public class Cpmparator_Comparable {
    @Test
    public void test1() {
        //没放comparator,就是自然排序.
        TreeSet ts = new TreeSet();
        //Description:不重复,会自动排序,自动调用Student类实现Comparable接口的compareTo方法进行比较(需要重写)
        ts.add(new Student("bc",12));
        ts.add(new Student("q",8));
        ts.add(new Student("q",8));
        ts.add(new Student("ab",12));
        ts.add(new Student("gf",42));
        ts.add(new Student("fgh",267));
        Iterator  it = ts.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }

    /**
     * Descriptio:
     * 定制排序，通过Comparator接口来实现。需要重写compare(T o1,T o2)方法。
     * 1.利用int compare(T o1,T o2)方法，比较o1和o2的大小：如果方法返回正整数，
     *    则表示o1大于o2；如果返回0，表示相等；返回负整数，表示o1小于o2。
     * 2.要实现定制排序，需要将实现Comparator接口的实例作为形参传递给TreeSet的构造器。
     */
    @Test
    public void test2() {
        Comparator comparator=new Comparator() {
            /**
             * 按照姓名,从小到大,再从年龄从小到大.
             * @param o1 the first object to be compared.
             * @param o2 the second object to be compared.
             * @return
             */
            public int compare(Object o1, Object o2) {
               if (o1 instanceof Student&&o2 instanceof Student) {
                   Student s1=(Student)o1;
                   Student s2=(Student)o2;

                   int i = s1.getName().compareTo(s2.getName());
                   if(i!=0){
                       return i;
                   }
                   return s1.getAge()-s2.getAge();

               }
               throw new RuntimeException("类型不匹配");
            }
        };
    //放了comparator就是定制排序
        TreeSet ts = new TreeSet(comparator);
        ts.add(new Student("bc",12));
        ts.add(new Student("q",8));
        ts.add(new Student("q",8));
        ts.add(new Student("ab",12));
        ts.add(new Student("gf",42));
        ts.add(new Student("fgh",267));
        Iterator  it = ts.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
